from flask import Blueprint, render_template, request, redirect, url_for, g
from exts import db
from models import UserModel, Exam, studentModel

# 这里定义的权限视图函数url前缀为"/stu"
bp = Blueprint("stu", __name__, url_prefix="/stu")


@bp.route("/", methods=['GET', 'POST'])
def stuIndex():
    id = g.user.id
    stu = studentModel.query.get(id)
    exams = []
    for asso in stu.exams:
        exams.append((Exam.query.get(asso.exam_id), asso.finished))
    return render_template('stu.html', exams=exams)


@bp.route("/info", methods=['GET', 'POST'])
def stuinfo():
    if request.method == 'GET':
        user = g.user
        return render_template("stuInfo.html", items=user)
    else:
        userName = request.form.get("userName")
        user = UserModel.query.filter_by(
            userName=userName, userType="student").first()
        if not user:
            print("该用户名不存在，请重新输入")
            return render_template("stuInfo.html", errorType=101)
        # 这里先暂时假设不能修改用户名
        passWord = request.form.get("passWord")
        trueName = request.form.get("trueName")
        schoolId = request.form.get("schoolId")
        school = request.form.get("school")
        major = request.form.get("major")
        user.passWord = passWord
        user.school = school
        user.trueName = trueName
        user.schoolId = schoolId
        user.major = major
        db.session.commit()
        return redirect(url_for("stu.stuIndex"))
